<template>
  <div
    class="view-container"
    :style="{
      width: widget.width + 'px',
      height: widget.height + 'px',
    }"
  >
    <div class="view-content">
      <div id="SetQRCode" ref="qrCodeRef"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, watch } from 'vue'
  import { useEleStore } from '@/store/modules/coms'
  import QRCode from 'qrcodejs2'
  import { translate } from '@/i18n'
  const props = defineProps<{
    index: number
  }>()
  const Store = useEleStore()
  const widget = computed(() => {
    return Store.getWidgets[props.index]
  })
  const qrCodeRef = ref(null) as any
  const setQRCode = () => {
    new QRCode(qrCodeRef.value, {
      text: widget.value.content,
      width: 80,
      height: 80,
      colorDark: widget.value.codeColor || '#000000',
      correctLevel: QRCode.CorrectLevel.L,
    })
  }
  watch(
    () => [widget.value?.content, widget.value?.codeColor],
    () => {
      nextTick(() => {
        if (widget.value && qrCodeRef.value) {
          while (qrCodeRef.value.firstChild) {
            qrCodeRef.value.removeChild(qrCodeRef.value.firstChild)
          }
          setQRCode()
        }
      })
    },
    { deep: true }
  )
  onMounted(() => {
    nextTick(() => {
      if (qrCodeRef.value) {
        setQRCode()
      }
    })
  })
</script>

<style lang="scss" scoped>
  .view-container {
    width: 100%;
    height: 100%;

    .view-content {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
    }
  }
  ::v-deep #SetQRCode img {
    height: 100%;
    width: 100%;
  }
</style>
